package com.voicechat.firstmet.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.AlipayBean;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PayResult;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.AlipaySerivice;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: GoldDepositsActivity
 * @Description: 充值金币界面
 * @Author: ljp
 * @CreateDate: 2018/10/8 13:57
 * @Version: 1.0
 */
public class GoldDepositsActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_60)
    TextView tv60;
    @BindView(R.id.tv_60_gold)
    TextView tv60Gold;
    @BindView(R.id.tv_6)
    TextView tv6;
    @BindView(R.id.rela_gold_deposits_6)
    RelativeLayout relaGoldDeposits6;
    @BindView(R.id.tv_360)
    TextView tv360;
    @BindView(R.id.tv_360_gold)
    TextView tv360Gold;
    @BindView(R.id.tv_36)
    TextView tv36;
    @BindView(R.id.rela_gold_deposits_360)
    RelativeLayout relaGoldDeposits360;
    @BindView(R.id.tv_990)
    TextView tv990;
    @BindView(R.id.tv_99_gold)
    TextView tv99Gold;
    @BindView(R.id.tv_99)
    TextView tv99;
    @BindView(R.id.rela_gold_deposits_990)
    RelativeLayout relaGoldDeposits990;
    @BindView(R.id.tv_1990)
    TextView tv1990;
    @BindView(R.id.tv_1990_gold)
    TextView tv1990Gold;
    @BindView(R.id.tv_199)
    TextView tv199;
    @BindView(R.id.rela_gold_deposits_1990)
    RelativeLayout relaGoldDeposits1990;
    @BindView(R.id.tv_5900)
    TextView tv5900;
    @BindView(R.id.tv_5900_gold)
    TextView tv5900Gold;
    @BindView(R.id.tv_590)
    TextView tv590;
    @BindView(R.id.rela_gold_deposits_5900)
    RelativeLayout relaGoldDeposits5900;
    @BindView(R.id.tv_9990)
    TextView tv9990;
    @BindView(R.id.tv_9990_gold)
    TextView tv9990Gold;
    @BindView(R.id.tv_999)
    TextView tv999;
    @BindView(R.id.rela_gold_deposits_9990)
    RelativeLayout relaGoldDeposits9990;
    @BindView(R.id.radio_zhifubao)
    RadioButton radioZhifubao;
    @BindView(R.id.radio_weixin)
    RadioButton radioWeixin;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.linear_weixin)
    LinearLayout linearWeixin;
    @BindView(R.id.linear_zhifubao)
    LinearLayout linearZhifubao;
    @BindView(R.id.tv_gold)
    TextView tvGold;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    private String TAG = "GoldDepositsActivity";
    private int diamondSum;
    private String payWay;//支付方式
    private String moneyPay;//充值金额
    private String moneyGold;//充值金币数
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private IWXAPI api;//微信支付
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        try {
                            JSONObject jsonObject = new JSONObject(resultInfo);
                            if (jsonObject.has("alipay_trade_app_pay_response")) {
                                JSONObject alipay_trade_app_pay_response = jsonObject.getJSONObject("alipay_trade_app_pay_response");
                                if (alipay_trade_app_pay_response.has("out_trade_no")) {
                                    String out_trade_no = alipay_trade_app_pay_response.getString("out_trade_no");
                                    judeRecharge(out_trade_no);//判断是否充值成功
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        toast_MakeText("支付已经取消");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showPopu();//弹出充值失败框
                    }
                    break;
                }
            }
        }
    };

    /**
     * @return
     * @method
     * @description 充值结果的判断
     * @date: 2019/1/10 10:09
     * @author: ljp
     */
    private void judeRecharge(String orderString) {
        AlipaySerivice.judeAlipayRecharge(orderString).subscribe(result -> {
            Log.i(TAG, "judeRecharge: -----" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                Intent intent = new Intent(activity, AllSuccessActivity.class);
                intent.putExtra("flag", "2");
                startActivity(intent);
                finish();
            } else {
                toast_MakeText(result.getMsg());
                showPopu();//弹出充值失败框
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            showPopu();//弹出充值失败框
            Log.i(TAG, "judeRecharge: ---------" + throwable.toString());
        });
    }

    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String deviceInfo;
    private String token;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_gold_deposits;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        diamondSum = getIntent().getIntExtra("diamondSum", 0);
        initView();
    }

    /**
     * @return
     * @method
     * @description 布局控件实例化
     * @date: 2018/10/9 19:49
     * @author: ljp
     */
    private void initView() {
        tvGold.setText(diamondSum + "");
        payWay = "Alipay";
        setLayoutBg(relaGoldDeposits6, tv60Gold, tv60, tv6);
    }

    /**
     * @return
     * @method
     * @description 充值失败
     * @date: 2018/11/6 18:03
     * @author: ljp
     */
    private void showPopu() {
        View view = View.inflate(context, R.layout.popi_pay_fail, null);
        PopUtils.showPopupWindow(activity, view, false);
        LinearLayout imageView = view.findViewById(R.id.image_close);
        TextView tvSure = view.findViewById(R.id.tv_sure);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
            }
        });

    }

    @OnClick({R.id.linear_back, R.id.rela_gold_deposits_6,
            R.id.rela_gold_deposits_360, R.id.rela_gold_deposits_990,
            R.id.rela_gold_deposits_1990, R.id.rela_gold_deposits_5900, R.id.rela_gold_deposits_9990
            , R.id.linear_zhifubao, R.id.linear_weixin, R.id.tv_pay,R.id.tv_recharge})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
               // context.startActivity(new Intent(context, MyWalletActivity.class));
                finish();
                break;
            case R.id.rela_gold_deposits_6:
                setLayoutCacalBg(relaGoldDeposits6, tv60Gold, tv60, tv6);
                break;
            case R.id.rela_gold_deposits_360:
                setLayoutCacalBg(relaGoldDeposits360, tv360Gold, tv360, tv36);
                break;
            case R.id.rela_gold_deposits_990:
                setLayoutCacalBg(relaGoldDeposits990, tv99Gold, tv990, tv99);
                break;
            case R.id.rela_gold_deposits_1990:
                setLayoutCacalBg(relaGoldDeposits1990, tv1990Gold, tv1990, tv199);
                break;
            case R.id.rela_gold_deposits_5900:
                setLayoutCacalBg(relaGoldDeposits5900, tv5900Gold, tv5900, tv590);
                break;
            case R.id.rela_gold_deposits_9990:
                setLayoutCacalBg(relaGoldDeposits9990, tv9990Gold, tv9990, tv999);
                break;
            case R.id.linear_zhifubao:
                setWay(view);
                break;
            case R.id.linear_weixin:
                setWay(view);
                break;
            case R.id.tv_pay://去支付R.id.tv_recharge
                toPay();
                break;
            case R.id.tv_recharge://充值服务协议
                Intent intent = new Intent(activity, WebPageActivity.class);
                intent.putExtra("url","file:///android_asset/web/recharge.html");
                intent.putExtra("title","充值服务协议");
                startActivity(intent);
                break;
        }
    }
    @Override
    public void onBackPressed() {
       // context.startActivity(new Intent(context, MyWalletActivity.class));
        finish();
    }

    /**
     * @return
     * @method
     * @description 去支付
     * @date: 2019/1/8 11:30
     * @author: ljp
     */

    private void toPay() {
        if (payWay.equals("Alipay")) {//支付宝支付
            AlipaySerivice.alipayRecharge(mySeleInfo.getNumber(), moneyPay + "," + moneyGold).subscribe(alipayBean -> {
                // Log.i(TAG, "toPay: ---------"+alipayBean.getMap().getOrderStr().toString());
                if (alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    setAlipay(alipayBean.getMap().getOrderStr());
                } else if (alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    Utils.setToken(context);
                } else {
                    toast_MakeText(alipayBean.getMsg());
                }
            }, throwable -> {
                toast_MakeText(getResources().getString(R.string.net_error));
                Log.i(TAG, "toPay: ---------" + throwable.toString());
            });
        } else {//微信支付
            AlipaySerivice.weixinRecharge(mySeleInfo.getNumber(), moneyPay + "," + moneyGold).subscribe(alipayBean -> {
                 Log.i(TAG, "toPay: ---------"+alipayBean.getCode());
                if (alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    Log.i(TAG, "toPay: --------"+alipayBean.getObject().toString());
                    setWeixinpay(alipayBean);
                } else if (alipayBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    Utils.setToken(context);
                } else {
                    toast_MakeText(alipayBean.getMsg());
                }
            }, throwable -> {
                toast_MakeText(getResources().getString(R.string.net_error));
                Log.i(TAG, "toPay: ---------" + throwable.toString());
            });

        }
    }
    /**
     * @return
     * @method
     * @description 微信支付
     * @date: 2019/1/10 10:44
     * @author: ljp
     */
    private void setWeixinpay(AlipayBean orderInfo) {
        api = WXAPIFactory.createWXAPI(this, "wxac01dfc5b7f1a911");
        api.registerApp("wxac01dfc5b7f1a911");
        PayReq req = new PayReq();
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        AlipayBean.ObjectBean object = orderInfo.getObject();
        req.appId = object.getAppId();
        req.partnerId= object.getPartnerid();
        req.prepayId= object.getPrepayid();
        req.packageValue= object.getPackageX();
        req.nonceStr= object.getNonceStr();
        req.timeStamp= object.getTimeStamp();
        req.sign= object.getSign();
        api.sendReq(req);
    }
    /**
     * @return
     * @method
     * @description 支付宝支付
     * @date: 2019/1/10 10:44
     * @author: ljp
     */
    private void setAlipay(String orderInfo) {
        final Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i(TAG, "run: -----------" + result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * @return
     * @method
     * @description 改变选定布局背景和字体颜色
     * @date: 2018/10/9 19:57
     * @author: ljp
     */
    private void setLayoutBg(RelativeLayout rela, TextView tvGold, TextView tvGoldtv, TextView tvMoney) {
        rela.setSelected(true);
        tvGold.setTextColor(getResources().getColor(R.color.colorFF3B5E));
        tvGoldtv.setTextColor(getResources().getColor(R.color.colorFF3B5E));
        tvMoney.setTextColor(getResources().getColor(R.color.colorFF8A9F));
        String money = tvMoney.getText().toString();
        this.moneyPay = money.substring(0, money.length() - 1);
        this.moneyGold = String.valueOf(Integer.parseInt(money.substring(0, money.length() - 1)) * 10);
        this.tvMoney.setText("￥" + money.substring(0, money.length() - 1) + ".00");
    }

    /**
     * @return
     * @method
     * @description 改变未选定布局背景和字体颜色
     * @date: 2018/10/9 19:57
     * @author: ljp
     */
    private void setLayoutUnseBg(RelativeLayout rela, TextView tvGold, TextView tvGoldtv, TextView tvMoney) {
        rela.setSelected(false);
        tvGold.setTextColor(getResources().getColor(R.color.color333333));
        tvGoldtv.setTextColor(getResources().getColor(R.color.color333333));
        tvMoney.setTextColor(getResources().getColor(R.color.color999999));
    }

    private void setLayoutCacalBg(RelativeLayout rela, TextView tvGold, TextView tvGoldtv, TextView tvMoney) {
        if (rela == relaGoldDeposits6) {
            setLayoutUnseBg(relaGoldDeposits360, tv360Gold, tv360, tv36);
            setLayoutUnseBg(relaGoldDeposits990, tv99Gold, tv990, tv99);
            setLayoutUnseBg(relaGoldDeposits1990, tv1990Gold, tv1990, tv199);
            setLayoutUnseBg(relaGoldDeposits5900, tv5900Gold, tv5900, tv590);
            setLayoutUnseBg(relaGoldDeposits9990, tv9990Gold, tv9990, tv999);
            setLayoutBg(rela, tvGold, tvGoldtv, tvMoney);
        } else if (rela == relaGoldDeposits360) {
            setLayoutUnseBg(relaGoldDeposits6, tv60Gold, tv60, tv6);
            setLayoutUnseBg(relaGoldDeposits990, tv99Gold, tv990, tv99);
            setLayoutUnseBg(relaGoldDeposits1990, tv1990Gold, tv1990, tv199);
            setLayoutUnseBg(relaGoldDeposits5900, tv5900Gold, tv5900, tv590);
            setLayoutUnseBg(relaGoldDeposits9990, tv9990Gold, tv9990, tv999);
            setLayoutBg(rela, tvGold, tvGoldtv, tvMoney);
        } else if (rela == relaGoldDeposits990) {
            setLayoutUnseBg(relaGoldDeposits6, tv60Gold, tv60, tv6);
            setLayoutUnseBg(relaGoldDeposits360, tv360Gold, tv360, tv36);
            setLayoutUnseBg(relaGoldDeposits1990, tv1990Gold, tv1990, tv199);
            setLayoutUnseBg(relaGoldDeposits5900, tv5900Gold, tv5900, tv590);
            setLayoutUnseBg(relaGoldDeposits9990, tv9990Gold, tv9990, tv999);
            setLayoutBg(rela, tvGold, tvGoldtv, tvMoney);
        } else if (rela == relaGoldDeposits1990) {
            setLayoutUnseBg(relaGoldDeposits6, tv60Gold, tv60, tv6);
            setLayoutUnseBg(relaGoldDeposits360, tv360Gold, tv360, tv36);
            setLayoutUnseBg(relaGoldDeposits990, tv99Gold, tv990, tv99);
            setLayoutUnseBg(relaGoldDeposits5900, tv5900Gold, tv5900, tv590);
            setLayoutUnseBg(relaGoldDeposits9990, tv9990Gold, tv9990, tv999);
            setLayoutBg(rela, tvGold, tvGoldtv, tvMoney);
        } else if (rela == relaGoldDeposits5900) {
            setLayoutUnseBg(relaGoldDeposits6, tv60Gold, tv60, tv6);
            setLayoutUnseBg(relaGoldDeposits360, tv360Gold, tv360, tv36);
            setLayoutUnseBg(relaGoldDeposits990, tv99Gold, tv990, tv99);
            setLayoutUnseBg(relaGoldDeposits1990, tv1990Gold, tv1990, tv199);
            setLayoutUnseBg(relaGoldDeposits9990, tv9990Gold, tv9990, tv999);
            setLayoutBg(rela, tvGold, tvGoldtv, tvMoney);
        } else if (rela == relaGoldDeposits9990) {
            setLayoutUnseBg(relaGoldDeposits6, tv60Gold, tv60, tv6);
            setLayoutUnseBg(relaGoldDeposits360, tv360Gold, tv360, tv36);
            setLayoutUnseBg(relaGoldDeposits990, tv99Gold, tv990, tv99);
            setLayoutUnseBg(relaGoldDeposits1990, tv1990Gold, tv1990, tv199);
            setLayoutUnseBg(relaGoldDeposits5900, tv5900Gold, tv5900, tv590);
            setLayoutBg(rela, tvGold, tvGoldtv, tvMoney);
        }
    }

    /**
     * @return
     * @method
     * @description radioButton支付方式的判断
     * @date: 2018/10/10 10:14
     * @author: ljp
     */
    private void setWay(View radioButton) {
        if (radioButton == linearZhifubao) {
            payWay = "Alipay";
            radioZhifubao.setChecked(true);
            radioWeixin.setChecked(false);
        } else if (radioButton == linearWeixin) {
            payWay = "WeChatPay";
            radioZhifubao.setChecked(false);
            radioWeixin.setChecked(true);
        }
    }
}
